package cool.taomu.toolkit.rpc.thrift.client.service

import com.google.inject.Inject
import cool.taomu.toolkit.inter.IFunction
import java.net.ConnectException
import java.util.concurrent.ConcurrentHashMap
import org.apache.commons.pool2.impl.GenericObjectPool
import org.apache.thrift.protocol.TCompactProtocol
import org.apache.thrift.protocol.TProtocol
import org.apache.thrift.transport.TTransport
import org.apache.thrift.transport.TTransportException
import org.apache.thrift.transport.layered.TFramedTransport
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory

@Accessors
class TaomuThriftTHsHaClient {

	val static LOG = LoggerFactory.getLogger(TaomuThriftTHsHaClient);

	@Inject
	ConcurrentHashMap<String, GenericObjectPool<TTransport>> poolMap;

	def get(String name, IFunction<TProtocol> client) {
		get(name, Integer.MAX_VALUE, client)
	}

	def get(String name, String host, int port, IFunction<TProtocol> client) {
		get(name, Integer.MAX_VALUE, client)
	}

	def get(String name, int maxLength, IFunction<TProtocol> client) {
		LOG.debug("获取连接池中的连接 poolMap containsKey {}:{}", name, poolMap.containsKey(name));
		if (poolMap.containsKey(name)) {
			var socket = poolMap.get(name).borrowObject;
			LOG.debug("连接到服务器操作1");
			try (var tTransport = new TFramedTransport(socket, maxLength)) {
				var protocol = new TCompactProtocol(tTransport);
				LOG.debug("连接到服务器操作2");
				client.apply(protocol);
			} catch (ConnectException | TTransportException ce) {
				LOG.debug("{}:连接异常\n{}", name, ce.message);
				if (poolMap.containsKey(name)) {
					LOG.debug("关闭{}连接池", name);
					poolMap.get(name) !== null ? poolMap.get(name).close;
					LOG.debug("移除{}", name);
					poolMap.remove(name);
				}
			} catch (Exception e) {
				LOG.debug("poolMap 中出现异常 key:{}", name);
				e.printStackTrace
			} finally {
				try {
					LOG.debug("执行连接归还操作:{}", name);
					if (poolMap.containsKey(name)) {
						poolMap.get(name).returnObject(socket); // 归还连接
					}
				} catch (Exception ignored) {
					ignored.printStackTrace
				}
			}
		}
	}

}
